using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.ProcessManagement;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ProcessManagements;

namespace RBAC.Write.Api.Application.Handler.ProcessManagements
{
    /// <summary>
    /// 批量删除工序（逻辑删除）处理器
    /// </summary>
    public class BatchDeleteProcessesHandler : IRequestHandler<BatchDeleteProcessesCommand, APIResult<int>>
    {
        private readonly IBaseRepository<ProcessInfo> _processRepo;
        private readonly ILogger<BatchDeleteProcessesHandler> _logger;

        public BatchDeleteProcessesHandler(
            IBaseRepository<ProcessInfo> processRepo,
            ILogger<BatchDeleteProcessesHandler> logger)
        {
            _processRepo = processRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BatchDeleteProcessesCommand request, CancellationToken cancellationToken)
        {
            var res = new APIResult<int>();
            try
            {
                if (request.Ids == null || request.Ids.Count == 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "请选择要删除的记录";
                    return Task.FromResult(res);
                }

                // 移除 UpdateTime/UpdateUser，避免与现有表结构不一致
                var sql = "UPDATE ProcessInfo SET IsDeleted=1 WHERE Id IN @Ids AND IsDeleted=0";
                var count = _processRepo.Execute(sql, new { Ids = request.Ids });

                res.Code = APIEnums.Success;
                res.Data = count;
                res.Msg = "删除成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除工序失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "批量删除工序异常";
                res.Data = 0;
            }
            return Task.FromResult(res);
        }
    }
}
